package com.kws.payment.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.chinaums.open.api.OpenApiCache;
import com.chinaums.open.api.OpenApiContext;
import com.chinaums.open.api.constants.ConfigBean;
import com.chinaums.open.api.internal.util.http.HttpTransport;
import com.kws.common.core.domain.R;
import com.kws.common.core.utils.StringUtils;
import com.kws.payment.dao.*;
import com.kws.payment.dao.info.CancelPayInfo;
import com.kws.payment.dao.info.RefundUnionPayWebInfo;
import com.kws.payment.dao.info.UnionPayWebInfo;
import com.kws.payment.service.UnionWebPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 * <b>UnionWebPayServiceImpl</b>
 *
 * @description: UnionWebPayServiceImpl <br>
 * @date: 2024/12/4 14:54 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class UnionWebPayServiceImpl implements UnionWebPayService {
    private static final Logger logger = LoggerFactory.getLogger(UnionWebPayServiceImpl.class);

    private static String QUERY_PAY_URL = " https://api-mop.chinaums.com/v1/netpay/bills/get-qrcode";

    private static String cancelPayUrl = "https://api-mop.chinaums.com/v1/netpay/bills/close-qrcode";

    private static String refundPayUrl = "https://api-mop.chinaums.com/v1/netpay/bills/refund";

    public String appId = "10037e6f6a4e6da4016a670fd4530012";

    public String appKey = "f7a74b6c02ae4e1e94aaba311c04acf2";

    public String mid = "898201612345678";

    public String tid = "88880001";

    @Override
    public String queryPayUrl(UnionPayRq rq) throws Exception {
        UnionPayWebRq unionPayWebRq = new UnionPayWebRq();
        unionPayWebRq.setMsgId(rq.getOrderNo());
        unionPayWebRq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        unionPayWebRq.setMid(mid);
        unionPayWebRq.setTid(tid);
        unionPayWebRq.setInstMid("QRPAYDEFAULT");
        unionPayWebRq.setBillNo(rq.getOrderNo());
        unionPayWebRq.setBillDate(DateUtil.format(new Date(),DatePattern.NORM_DATE_FORMATTER));
        unionPayWebRq.setBillDesc(rq.getOrderDesc());
        unionPayWebRq.setNotifyUrl("支付回调地址");
        unionPayWebRq.setTotalAmount(rq.getTotalAmount());
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(QUERY_PAY_URL.split("/v")[0].concat("/"));
        context.setApiServiceUrl(QUERY_PAY_URL);
        context.setVersion(QUERY_PAY_URL.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(QUERY_PAY_URL.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);
        String str = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(JSONUtil.parse(unionPayWebRq)));
        if (StringUtils.isNotEmpty(str)){
            UnionPayWebInfo info = JSONUtil.toBean(str, UnionPayWebInfo.class);
            if ("SUCCESS".equals(info.getErrCode()) && "0000".equals(info.getErrMsg())){
                return info.getBillQRCode();
            }
        }
        return null;
    }

    @Override
    public R cancelPay(String qrCodeId) throws Exception {
        CancelPayRq cancelPayRq = new CancelPayRq();
        cancelPayRq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        cancelPayRq.setMid(mid);
        cancelPayRq.setTid(tid);
        cancelPayRq.setInstMid("QRPAYDEFAULT");
        cancelPayRq.setQrCodeId(qrCodeId);
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(cancelPayUrl.split("/v")[0].concat("/"));
        context.setApiServiceUrl(cancelPayUrl);
        context.setVersion(cancelPayUrl.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(cancelPayUrl.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);
        String str = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(JSONUtil.parse(cancelPayRq)));
        if (StringUtils.isNotEmpty(str)){
            CancelPayInfo info = JSONUtil.toBean(str, CancelPayInfo.class);
            if ("SUCCESS".equals(info.getErrCode()) && "0000".equals(info.getErrMsg())){
                return R.ok("取消成功");
            }else {
                return R.fail("取消失败");
            }
        }
        return R.fail("取消失败");
    }

    @Override
    public R refundUnionWebPay(RefundUnionPayRq rq) throws Exception {
        RefundUnionPayWebRq refundUnionPayWebRq = new RefundUnionPayWebRq();
        refundUnionPayWebRq.setMsgId(rq.getOrderNo());
        refundUnionPayWebRq.setRequestTimestamp(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        refundUnionPayWebRq.setMid(mid);
        refundUnionPayWebRq.setTid(tid);
        refundUnionPayWebRq.setInstMid("QRPAYDEFAULT");
        refundUnionPayWebRq.setBillNo(rq.getOrderNo());
        refundUnionPayWebRq.setRefundOrderId(rq.getRefundOrderId());
        refundUnionPayWebRq.setBillDate(DateUtil.format(new Date(),DatePattern.NORM_DATE_FORMATTER));
        refundUnionPayWebRq.setRefundAmount(rq.getRefundAmount());
        ConfigBean configBean = new ConfigBean();
        OpenApiContext context = new OpenApiContext();
        context.setStartTime(System.currentTimeMillis());
        context.setRequestId(UUID.randomUUID().toString().replace("-", ""));
        context.setOpenServUrl(refundPayUrl.split("/v")[0].concat("/"));
        context.setApiServiceUrl(refundPayUrl);
        context.setVersion(refundPayUrl.split("/")[3]);
        context.setAppId(appId);
        context.setAppKey(appKey);
        context.setConfigBean(configBean);
        context.setServiceCode(refundPayUrl.split("/v")[1].substring(1));
        OpenApiCache.getCurrentToken(context);
        String str = HttpTransport.getInstance().doPost(context, JSONUtil.toJsonStr(JSONUtil.parse(refundUnionPayWebRq)));
        if (StringUtils.isNotEmpty(str)){
            RefundUnionPayWebInfo info = JSONUtil.toBean(str, RefundUnionPayWebInfo.class);
            if ("SUCCESS".equals(info.getErrCode()) && "0000".equals(info.getErrMsg())){
                return R.ok(info);
            }else {
                return R.fail("取消失败");
            }
        }
        return null;
    }
}
